package com.hwua.dao.Impl;

import com.hwua.Util.C3P0Util;
import com.hwua.dao.IProductDao;
import com.hwua.entity.Product;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.util.List;

public class ProductDaoImpl implements IProductDao {
    private QueryRunner queryRunner=null;

    public ProductDaoImpl() {
        queryRunner=new QueryRunner(C3P0Util.getCpds());
    }

    @Override
    public List<Product> queryAll() throws Exception {
        String sql="SELECT * from amz_product ORDER BY stock DESC limit 1,6";
        return queryRunner.query(sql,new BeanListHandler<Product>(Product.class));
    }

    @Override
    public List<Product> query() throws Exception {
        String sql="SELECT * from amz_product ORDER BY stock DESC";
        return queryRunner.query(sql,new BeanListHandler<Product>(Product.class));
    }

    @Override
    public List<Product> queryAllForLimit( Integer start, Integer pageSize) throws Exception {
        String sql = "select * from amz_product limit ?,?";
        Object[] args = { start, pageSize};
        return queryRunner.query(sql, new BeanListHandler<Product>(Product.class), args);
    }

    @Override
    public Long queryCount() throws Exception {
        String sql="select count(*) from amz_product";
        Long count = 0L;
        try {
            count = queryRunner.query(sql,new ScalarHandler<>());
        } catch (Exception e) {
            return null;
        }
        return count;
    }

    @Override
    public List<Product> queryById(int minor_id) throws Exception {
        String sql="select * from amz_product where minor_id=?";
        Object[] args={minor_id};
        return queryRunner.query(sql,new BeanListHandler<Product>(Product.class),args);
    }

    @Override
    public Product queryByProdId(int id) throws Exception {
        String sql="select * from amz_product where id=?";
        Object[] args={id};
        return queryRunner.query(sql,new BeanHandler<Product>(Product.class),args);
    }


    public List<Product> queryProById(int id) throws Exception {
        String sql="select * from amz_product where id=?";
        Object[] args={id};
        return queryRunner.query(sql,new BeanListHandler<Product>(Product.class),args);
    }

    @Override
    public Product queryByMinorID(int minor_id) throws Exception {
        String sql="select * from amz_product where minor_id=?";
        Object[] args={minor_id};
        return queryRunner.query(sql,new BeanHandler<Product>(Product.class),args);
    }

    @Override
    public List<Product> queryByMajor_id(int Major_id) throws Exception {
        String sql="select * from amz_product where major_id=?";
        Object[] args={Major_id};
        return queryRunner.query(sql,new BeanListHandler<Product>(Product.class),args);
    }
}
